<template>
  <div class="admin-users">
    <el-card class="users-card">
      <template #header>
        <div class="card-header">
          <h3>用户管理</h3>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户"
              class="search-input"
              prefix-icon="el-icon-search"
              clearable
              @clear="handleSearch"
              @input="handleSearch"
            />
            <el-button type="primary" @click="handleAddUser">添加用户</el-button>
          </div>
        </div>
      </template>

      <!-- 用户类型切换 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="教师用户" name="teacher"></el-tab-pane>
        <el-tab-pane label="学生用户" name="student"></el-tab-pane>
        <el-tab-pane label="管理员" name="admin"></el-tab-pane>
      </el-tabs>

      <!-- 用户列表表格 -->
      <el-table :data="filteredUsers" style="width: 100%" v-loading="loading">
        <el-table-column label="用户ID" prop="id" width="80" />
        <el-table-column label="用户名" prop="username" width="120" />
        <el-table-column label="真实姓名" prop="realName" width="120" />
        <el-table-column label="角色" width="100">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ getRoleName(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="邮箱" prop="email" />
        <el-table-column label="手机号" prop="phone" width="130" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="(val) => handleStatusChange(scope.row, val)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleResetPassword(scope.row)">重置密码</el-button>
            <el-button type="text" size="small" class="danger-text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form :model="userForm" :rules="rules" ref="userFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="0" />
            <el-option label="教师" value="1" />
            <el-option label="学生" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="userForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 数据加载状态
const loading = ref(false);

// 用户列表数据
const userList = ref([]);
const filteredUsers = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);

// 搜索关键词
const searchKeyword = ref('');

// 当前选中的标签页
const activeTab = ref('teacher');

// 对话框相关
const dialogVisible = ref(false);
const dialogType = ref('add'); // 'add' 或 'edit'
const userFormRef = ref(null);
const userForm = reactive({
  id: '',
  username: '',
  realName: '',
  role: '',
  email: '',
  phone: '',
  password: '',
  status: 1
});

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', when: () => dialogType.value === 'add' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
};

// 初始化
onMounted(() => {
  loadUserData();
});

// 加载用户数据
const loadUserData = async () => {
  loading.value = true;
  try {
    // 这里应该调用API获取用户数据
    // 以下是模拟数据
    setTimeout(() => {
      const mockData = [];
      // 生成30个教师用户
      for (let i = 1; i <= 30; i++) {
        mockData.push({
          id: 1000 + i,
          username: `teacher${i}`,
          realName: `教师${i}`,
          role: '1',
          email: `teacher${i}@example.com`,
          phone: `1366666${i.toString().padStart(4, '0')}`,
          createTime: new Date(2023, 0, i).getTime(),
          status: 1
        });
      }
      // 生成50个学生用户
      for (let i = 1; i <= 50; i++) {
        mockData.push({
          id: 2000 + i,
          username: `student${i}`,
          realName: `学生${i}`,
          role: '2',
          email: `student${i}@example.com`,
          phone: `1388888${i.toString().padStart(4, '0')}`,
          createTime: new Date(2023, 1, i).getTime(),
          status: 1
        });
      }
      // 生成5个管理员用户
      for (let i = 1; i <= 5; i++) {
        mockData.push({
          id: 100 + i,
          username: `admin${i}`,
          realName: `管理员${i}`,
          role: '0',
          email: `admin${i}@example.com`,
          phone: `1399999${i.toString().padStart(4, '0')}`,
          createTime: new Date(2023, 2, i).getTime(),
          status: 1
        });
      }
      
      userList.value = mockData;
      filterUsersByTab();
      loading.value = false;
    }, 500);
  } catch (error) {
    console.error('加载用户数据失败', error);
    ElMessage.error('加载用户数据失败');
    loading.value = false;
  }
};

// 根据标签页筛选用户
const filterUsersByTab = () => {
  const roleMap = {
    'teacher': '1',
    'student': '2',
    'admin': '0'
  };
  
  let filtered = userList.value.filter(user => user.role === roleMap[activeTab.value]);
  
  // 应用搜索关键词
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(user => 
      user.username.toLowerCase().includes(keyword) || 
      user.realName.toLowerCase().includes(keyword) || 
      user.email.toLowerCase().includes(keyword) || 
      user.phone.includes(keyword)
    );
  }
  
  // 计算总数
  totalCount.value = filtered.length;
  
  // 应用分页
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  filteredUsers.value = filtered.slice(start, end);
};

// 处理标签页变化
const handleTabChange = () => {
  currentPage.value = 1;
  filterUsersByTab();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  filterUsersByTab();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size;
  filterUsersByTab();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page;
  filterUsersByTab();
};

// 获取角色名称
const getRoleName = (role) => {
  const roleMap = {
    '0': '管理员',
    '1': '教师',
    '2': '学生'
  };
  return roleMap[role] || '未知';
};

// 获取角色标签类型
const getRoleTagType = (role) => {
  const typeMap = {
    '0': 'danger',
    '1': 'primary',
    '2': 'success'
  };
  return typeMap[role] || 'info';
};

// 格式化日期
const formatDate = (timestamp) => {
  const date = new Date(timestamp);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 处理添加用户
const handleAddUser = () => {
  dialogType.value = 'add';
  // 重置表单
  Object.keys(userForm).forEach(key => {
    userForm[key] = '';
  });
  userForm.status = 1;
  // 根据当前标签页设置默认角色
  const roleMap = {
    'teacher': '1',
    'student': '2',
    'admin': '0'
  };
  userForm.role = roleMap[activeTab.value];
  
  dialogVisible.value = true;
  // 等待DOM更新后重置表单验证
  setTimeout(() => {
    userFormRef.value?.resetFields();
  }, 0);
};

// 处理编辑用户
const handleEdit = (row) => {
  dialogType.value = 'edit';
  // 复制用户数据到表单
  Object.keys(userForm).forEach(key => {
    if (key !== 'password') { // 编辑时不填充密码
      userForm[key] = row[key];
    }
  });
  
  dialogVisible.value = true;
  // 等待DOM更新后重置表单验证
  setTimeout(() => {
    userFormRef.value?.clearValidate();
  }, 0);
};

// 处理删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 ${row.realName} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API删除用户
    // 以下是模拟操作
    const index = userList.value.findIndex(item => item.id === row.id);
    if (index !== -1) {
      userList.value.splice(index, 1);
      filterUsersByTab();
      ElMessage.success('删除成功');
    }
  }).catch(() => {});
};

// 处理重置密码
const handleResetPassword = (row) => {
  ElMessageBox.confirm(`确定要重置用户 ${row.realName} 的密码吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用API重置密码
    // 以下是模拟操作
    ElMessage.success(`用户 ${row.realName} 的密码已重置为默认密码`);
  }).catch(() => {});
};

// 处理状态变更
const handleStatusChange = (row, value) => {
  // 这里应该调用API更新用户状态
  // 以下是模拟操作
  const statusText = value === 1 ? '启用' : '禁用';
  ElMessage.success(`已${statusText}用户 ${row.realName}`);
};

// 提交表单
const submitForm = () => {
  userFormRef.value?.validate((valid) => {
    if (valid) {
      // 这里应该调用API保存用户
      // 以下是模拟操作
      if (dialogType.value === 'add') {
        // 添加用户
        const newUser = { ...userForm };
        newUser.id = Date.now(); // 模拟ID生成
        newUser.createTime = new Date().getTime();
        userList.value.push(newUser);
        ElMessage.success('添加成功');
      } else {
        // 更新用户
        const index = userList.value.findIndex(item => item.id === userForm.id);
        if (index !== -1) {
          userList.value[index] = { ...userList.value[index], ...userForm };
          ElMessage.success('更新成功');
        }
      }
      
      dialogVisible.value = false;
      filterUsersByTab();
    }
  });
};
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

.users-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.danger-text {
  color: #F56C6C;
}

.danger-text:hover {
  color: #f78989;
}
</style> 